import React, { useState, useEffect, useMemo, useRef } from 'react'
import FooterNav from "@/components/footer-nav"
import GetPullToRefreshlData from "./components/RefeshData/index";
import GetPublicPullToRefreshlData from "./components/PublicRefeshData/index";
import { connect } from "react-redux"
import styles from "./index.module.less"
import {DotLoading, SearchBar} from 'antd-mobile'
import { showErrorToast } from '@/utils/customToast';
const { getCategory, getWorldCategoryList } = $globalServicer('home')
const { setShopNum } = $globalReduxAction('common')

const Home = () => {
    const [navList, setNavList] = useState([])
    const [activeKey, setActiveKey] = useState(null); // 初始化为null，等待API数据加载
    
    // 分类筛选相关状态
    const [showCategoryModal, setShowCategoryModal] = useState(false);
    const [selectedTags, setSelectedTags] = useState(new Set());
    const [categoryList, setCategoryList] = useState([]); // 从API获取的分类列表
    const [loadingCategories, setLoadingCategories] = useState(false);
    const [allCategoriesMap, setAllCategoriesMap] = useState(new Map()); // 存储所有分类的映射
    
    // 搜索相关状态
    const [searchValue, setSearchValue] = useState('');
    const [searchTimer, setSearchTimer] = useState(null);
    
    // 用于调用子组件方法的ref
    const refreshDataRef = useRef();

    // 使用useMemo来避免selectedCategories数组的重复创建
    const selectedCategoriesArray = useMemo(() => {
        return Array.from(selectedTags);
    }, [selectedTags]);

    useEffect(() => {
        getCategoryList()
    }, [])

    // 组件卸载时清理定时器
    useEffect(() => {
        return () => {
            if (searchTimer) {
                clearTimeout(searchTimer);
            }
        };
    }, [searchTimer])

    // 获取分类
    const getCategoryList = async () => {
        try {
            const res = await getCategory()
            const newNavList = [].concat(res)
            setNavList(newNavList)
            
            // 设置默认的activeKey - 如果还没有设置activeKey，则使用第一个非公告分类
            if (activeKey === null && newNavList.length > 0) {
                // 找到第一个非公告分类（id不为0的分类）
                const defaultCategory = newNavList.find(item => item.id !== 0);
                const defaultActiveKey = defaultCategory ? defaultCategory.id : (newNavList[0]?.id || 0);
                setActiveKey(defaultActiveKey);
                
                // 如果不是公告页面，加载对应的分类数据
                if (defaultActiveKey !== 0) {
                    fetchCategoryList(defaultActiveKey);
                }
            } else if (activeKey !== null && activeKey !== 0) {
                // 如果activeKey已经设置且不是公告页面，加载分类数据
                fetchCategoryList(activeKey);
            }
        } catch (error) {
            console.error('获取一级分类失败:', error);
            // 如果API失败，设置默认值避免一直为null
            if (activeKey === null) {
                setActiveKey(0); // 默认显示公告页面
            }
        }
    }

    // 获取子分类列表
    const fetchCategoryList = async (categoryId) => {
        try {
            setLoadingCategories(true);
            const response = await getWorldCategoryList(categoryId);
            // 根据API返回结构处理数据
            const categoryData = response.data || response;
            if (Array.isArray(categoryData)) {
                setCategoryList(categoryData);
                
                // 更新全局分类映射
                const newMap = new Map(allCategoriesMap);
                categoryData.forEach(category => {
                    newMap.set(category.id, category.name);
                });
                setAllCategoriesMap(newMap);
            } else {
                console.warn('分类数据格式不正确:', categoryData);
                setCategoryList([]);
            }
        } catch (error) {
            console.error('获取分类列表失败:', error);
            showErrorToast("加载分类失败，请稍后再试");
        } finally {
            setLoadingCategories(false);
        }
    };

    const handleTabChange = (key) => {
        // 防止重复点击同一个tab
        if (key === activeKey) {
            return;
        }

        // 清除之前的搜索定时器，避免干扰
        if (searchTimer) {
            clearTimeout(searchTimer);
            setSearchTimer(null);
        }

        // 立即更新activeKey和重置相关状态
        setActiveKey(key);
        setSelectedTags(new Set());
        setSearchValue(''); // 清空搜索框
        
        // 如果不是公告页面，加载对应的分类数据并加载列表数据
        if (key !== 0) {
            fetchCategoryList(key);
            
            // 直接调用数据加载，不使用延迟
            if (refreshDataRef.current) {
                refreshDataRef.current.loadData(key, '', []); // categoryId, searchKey, selectedCats
            }
        } else {
            // 如果是公告页面，清空分类列表
            setCategoryList([]);
        }
    };

    // 分类筛选相关函数
    const toggleCategoryModal = () => {
        setShowCategoryModal(!showCategoryModal);
    };

    const closeCategoryModal = () => {
        setShowCategoryModal(false);
    };

    const handleTagClick = (tag) => {
        // 单选逻辑：点击标签时，如果已选中则取消选择，否则选中该标签
        if (selectedTags.has(tag)) {
            setSelectedTags(new Set());
        } else {
            setSelectedTags(new Set([tag]));
        }
    };

    const clearSelection = () => {
        setSelectedTags(new Set());
        closeCategoryModal();
        
        // 使用新的统一方法
        if (refreshDataRef.current) {
            refreshDataRef.current.loadData(activeKey, searchValue, []);
        }
    };

    const applySelection = () => {
        const selectedCategoryIds = Array.from(selectedTags);
        console.log('Selected category IDs:', selectedCategoryIds);
        
        closeCategoryModal();
        
        // 使用新的统一方法
        if (refreshDataRef.current) {
            refreshDataRef.current.loadData(activeKey, searchValue, selectedCategoryIds);
        }
    };

    // 搜索框防抖处理函数
    const handleSearchWithDebounce = (value) => {
        // 清除之前的定时器
        if (searchTimer) {
            clearTimeout(searchTimer);
        }
        
        // 设置新的防抖定时器
        const newTimer = setTimeout(() => {
            if (refreshDataRef.current && activeKey !== 0) {
                // 使用新的统一方法
                refreshDataRef.current.loadData(activeKey, value, selectedCategoriesArray);
            }
        }, 500); // 500ms 防抖延迟
        
        setSearchTimer(newTimer);
    };

    return (
        <div className={styles.container}>
            <header className={styles.header}>
                <div className={styles.topTabs}>
                    {navList.map(f => (
                        <a 
                            key={f.id} 
                            className={`${styles.tabLink} ${activeKey === f.id ? styles.activeTab : styles.inactiveTab}`} 
                            href="#" 
                            onClick={(e) => {
                                e.preventDefault();
                                handleTabChange(f.id);
                            }}
                        >
                            {f.name}
                        </a>
                    ))}
                </div>
                <button className={styles.categoryToggle} onClick={toggleCategoryModal}>
                    <i className="material-icons">category</i>
                    <span className={styles.categoryText}>分类</span>
                    {selectedTags.size > 0 && (
                        <span className={styles.selectedCountBadge}>1</span>
                    )}
                    <i className="material-icons">expand_more</i>
                </button>
            </header>

            <div className={styles.searchWrapper}>
                <SearchBar
                    placeholder='搜索智能体'
                    style={{
                        '--border-radius': '100px',
                        '--background': 'var(--theme-bg-input)',
                        '--background-color': 'var(--theme-bg-input)',
                        '--height': '50px',
                        '--padding-left': '12px',
                        '--color': 'var(--theme-text-primary)',
                        '--placeholder-color': 'var(--theme-text-muted)',
                        '--font-size': '14px',
                        '--cancel-color': 'var(--theme-text-primary)',
                        '--adm-color-background': 'var(--theme-bg-input)',
                        '--adm-color-primary': 'var(--theme-bg-input)',
                        width: '100%',
                    }}
                    className={styles.searchBar}
                    value={searchValue}
                    onChange={(value) => {
                        setSearchValue(value);
                        handleSearchWithDebounce(value);
                    }}
                    onSearch={handleSearchWithDebounce}
                    onClear={() => {
                        setSearchValue('');
                        // 清除搜索定时器
                        if (searchTimer) {
                            clearTimeout(searchTimer);
                            setSearchTimer(null);
                        }
                        if (refreshDataRef.current && activeKey !== 0) {
                            refreshDataRef.current.setSearchValue('');
                        }
                    }}
                />
            </div>

            <main className={styles.mainContent}>
                {activeKey === null ? (
                    <div className={styles.loadingContainer}>
                        <div className={styles.loadingContent}>
                            <DotLoading color={getComputedStyle(document.documentElement).getPropertyValue('--theme-primary').trim()}/>
                            <div className={styles.loadingText}>正在加载，请稍等...</div>
                        </div>
                    </div>
                ) : (
                    <GetPullToRefreshlData
                        ref={refreshDataRef}
                        activeKey={activeKey}
                        selectedCategories={selectedCategoriesArray}
                        onCategoryChange={setSelectedTags}
                        allCategoriesMap={allCategoriesMap}
                    />
                )}
            </main>

            {/* 分类筛选模态框 */}
            {showCategoryModal && (
                <>
                    <div className={styles.categoryOverlay} onClick={closeCategoryModal}></div>
                    <div className={styles.categoryPanel}>
                        <div className={styles.categoryModal}>
                            <div className={styles.categoryHeader}>
                                <div className={styles.categoryTitle}>分类筛选</div>
                                <div className={styles.categoryControls}>
                                    <button className={styles.closeButton} onClick={closeCategoryModal}>
                                        <i className="material-icons">close</i>
                                    </button>
                                </div>
                            </div>
                            <div className={styles.categoryContent}>
                                <div className={styles.tagList}>
                                    {loadingCategories ? (
                                        <div className={styles.loadingContainer}>
                                            <div className={styles.loadingContent}>
                                                <DotLoading color={getComputedStyle(document.documentElement).getPropertyValue('--theme-primary').trim()}/>
                                                <div className={styles.loadingText}>正在加载，请稍等...</div>
                                            </div>
                                        </div>
                                    ) : categoryList.length > 0 ? (
                                        categoryList.map(category => (
                                            <button
                                                key={category.id}
                                                className={`${styles.tagButton} ${selectedTags.has(category.id) ? styles.tagButtonSelected : styles.tagButtonUnselected}`}
                                                onClick={() => handleTagClick(category.id)}
                                            >
                                                {category.name}
                                            </button>
                                        ))
                                    ) : (
                                        <div className={styles.noDataText}>
                                            暂无分类数据
                                        </div>
                                    )}
                                </div>
                            </div>
                            <div className={styles.categoryFooter}>
                                <button className={styles.clearButton} onClick={clearSelection}>
                                    清空
                                </button>
                                <button className={styles.applyButton} onClick={applySelection}>
                                    完成
                                </button>
                            </div>
                        </div>
                    </div>
                </>
            )}

            <FooterNav></FooterNav>
        </div>
    );
};
const mapStateToProps = (state) => state.common;
const mapDispatchToProps = { setShopNum };
export default connect(mapStateToProps, mapDispatchToProps)(Home);
